package context.bfpp;

import context.editor.A;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.*;
import org.springframework.stereotype.Component;
import service.DbConfigService;

import java.util.Properties;

/**
 * 模拟配置中心:从数据库拉取配置
 */
@Component
public class ConfigCenterBFPP implements EnvironmentAware, BeanFactoryPostProcessor, PriorityOrdered, ApplicationContextAware {

	private Environment environment;
	private ApplicationContext context;
	private static final String PROPERTIES_KEY = "dbConfig";
	private static final Properties dbConfigMap = new Properties();
	static {
		dbConfigMap.put("username", "root");
		dbConfigMap.put("password", "root");
	}

	@Autowired
	private DbConfigService dbConfigService;

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		if (this.environment != null) {
			DbConfigService bean = context.getBean(DbConfigService.class);
			if (this.environment instanceof StandardEnvironment) {
				StandardEnvironment standardEnvironment = (StandardEnvironment) this.environment;
				MutablePropertySources propertySources = standardEnvironment.getPropertySources();
				// 从数据库中获取配置
				PropertySource<?> dbPropertySource =
						new PropertiesPropertySource(PROPERTIES_KEY, dbConfigMap);
				propertySources.addLast(dbPropertySource);
			}
		}
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}
}
